package com.my.lucky7.upload;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.google.gson.Gson;
import com.my.lucky7.common.LocalCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;

@Component
@Slf4j
public class AliyunOSSImageUploader {

    // 阿里云账号AccessKey信息（建议从环境变量或配置文件中获取）
    private static final String ACCESS_KEY_ID = "LTAI5t5vGa22VRU6xb7JjEMK";
    private static final String ACCESS_KEY_SECRET = "7RyYqnPUVC8VGwZFpEQLCNk2UnXw5Q";
    private static final String HOST_PATH = "https://luck7-gallery.oss-cn-beijing.aliyuncs.com/";
    // OSS相关配置
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com"; // 根据你的Bucket所在地区修改
    public static final String BUCKET_NAME = "luck7-gallery";
    private static final String OBJECT_NAME = "gallery/"; // 对象在OSS中的存储路径
    private static final String LOCAL_FILE_PATH = "path/to/your/local/image.jpg"; // 本地图片路径
    // http://luck7-gallery.luck7-gallery.oss-cn-beijing.aliyuncs.com/gallery/%E6%9C%BA%E5%99%A8%E4%BA%BA.jpg?Expires=1745418772&OSSAccessKeyId=LTAI5t5vGa22VRU6xb7JjEMK&Signature=i7UIxFmIrI9prMCDJPTD3CpzrrM%3D
    // https://luck7-gallery.oss-cn-beijing.aliyuncs.com/gallery/%E6%9C%BA%E5%99%A8%E4%BA%BA.jpg
    private OSS ossClient;

    @Resource
    LocalCache localCache;

    @Bean
    public OSS ossClient() {
        if(ossClient == null){
            ossClient = new OSSClientBuilder().build(
                    ENDPOINT,
                    new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET),
                    null
            );
        }
        return ossClient;
    }

    public void removeImage(String fileName) throws ClientException {
        ossClient.deleteObject(BUCKET_NAME, fileName);
    }

    public static void main(String[] args) {
        // 创建OSS客户端实例
        OSS ossClient = new OSSClientBuilder().build(
                ENDPOINT,
                new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET),
                null
        );

        try {
            // 1. 上传图片到OSS
            uploadImage(ossClient);
            
            // 2. 生成临时访问链接
//            String url = generateTempUrl(ossClient);
//            System.out.println("临时访问链接: " + url);
//            System.out.println("链接有效期至: " + new Date(System.currentTimeMillis() + 3600 * 1000));
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }

    /**
     * 上传图片到OSS
     */
    public String uploadImage(String fileName, InputStream fis) throws ClientException {
        String uploadFileName = OBJECT_NAME + DateUtil.format(new Date(), "yyyyMMddHHmmss") + "/" + fileName;
        // 创建PutObject请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                BUCKET_NAME,
                uploadFileName,
                fis
        );
        // 执行上传
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        log.info("图片上传成功 {}", new Gson().toJson(result));
        return HOST_PATH + BUCKET_NAME + "/" + uploadFileName;
    }

    /**
     * 上传图片到OSS
     */
    private static void uploadImage(OSS ossClient) throws ClientException {
        // 创建PutObject请求
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                BUCKET_NAME,
                OBJECT_NAME,
                new File(LOCAL_FILE_PATH)
        );

        // 执行上传
        ossClient.putObject(putObjectRequest);
        System.out.println("图片上传成功");
    }

    /**
     * 生成临时访问链接
     */
    public String generateTempUrl(String bucketName, String objectName, int scale) {
        // 设置本地缓存25分钟,存在就直接返回
        String key = bucketName + ":" + objectName + ":" + scale;
        Object tempCacheUrl = localCache.get(key);
        if(null != tempCacheUrl){
            return tempCacheUrl.toString();
        }
        // 原始尺寸的30%
        String style = "image/resize,p_" + scale;
        // 创建生成临时链接请求
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
                bucketName,
                objectName,
                com.aliyun.oss.HttpMethod.GET
        );

        // 设置链接有效期（单位：毫秒，这里设置为0.5小时）
        Long ttl = 1800 * 1000L;
        request.setExpiration(new Date(System.currentTimeMillis() + ttl));
        request.setProcess(style);

        // 生成临时链接
        URL signedUrl = ossClient.generatePresignedUrl(request);
        localCache.put(key, signedUrl.toString(), ttl);
        return signedUrl.toString();
    }
}